package com.shopmall.manager.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.shopmall.common.exception.CustomException;
import com.shopmall.manager.mapper.SysRoleUserMapper;
import com.shopmall.manager.mapper.SysUserMapper;
import com.shopmall.manager.service.SysUserService;
import com.shopmall.model.dto.system.AssginRoleDto;
import com.shopmall.model.dto.system.LoginDto;
import com.shopmall.model.dto.system.SysUserDto;
import com.shopmall.model.entity.system.SysUser;
import com.shopmall.model.vo.common.ResultCodeEnum;
import com.shopmall.model.vo.system.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private SysRoleUserMapper sysRoleUserMapper;

    // 用户登录
    @Override
    public LoginVo login(LoginDto loginDto) {
        // 获取输入验证码和存储到redis的key名称
        String captcha = loginDto.getCaptcha();
        String key = loginDto.getCodeKey();
        // 获取redis里面的key，查询redis里面存储的验证码
        String redisCode = redisTemplate.opsForValue().get("user:validate" + key);
        // 比较输入的验证码和redis存储验证码是否一致
        if (StrUtil.isEmpty(redisCode) || !StrUtil.equalsIgnoreCase(redisCode, captcha)) {
            throw new CustomException(ResultCodeEnum.VALIDATECODE_ERROR);
        }
        // 如果不一致，提示用户，校检失败，删除redis里验证码
        redisTemplate.delete("user:validate" + key);
        // 1、获取提交用户名，loginDto获取到
        String userName = loginDto.getUserName();
        // 2、根据用户名查询过数据库表sys_user表
        SysUser sysUser = sysUserMapper.selectUserInfoByUserName(userName);
        // 3、根据用户名查不到对应信息，用户不存在，返回错误信息
        if (sysUser == null) {
//            throw new RuntimeException("用户名不存在");
            throw new CustomException(ResultCodeEnum.LOGIN_ERROR);
        }
        // 4、用户存在，获取输入密码，比较输入的密码和数据库密码是否一致
        String database_password = sysUser.getPassword();
        // 密码加密后再比较暗，MD5
        String input_password = DigestUtils.md5DigestAsHex(loginDto.getPassword().getBytes());
        // 比较密码
        if (!input_password.equals(database_password)) {
//            throw new RuntimeException("密码不正确");
            throw new CustomException(ResultCodeEnum.LOGIN_ERROR);
        }
        // 5、密码一致，登录成功，生成唯一标识token
        String token = UUID.randomUUID().toString().replace("-", "");
        // 6、把登录成功用户信息放到Redis，key: token, value: 用户信息
        redisTemplate.opsForValue()
                .set("user:login" + token,
                        JSON.toJSONString(sysUser),
                        7,
                        TimeUnit.DAYS
                );
        // 7、返回LoginVo对象
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        return loginVo;
    }

    // 获取用户信息
    @Override
    public SysUser getUserInfo(String token) {
        String userJson = redisTemplate.opsForValue().get("user:login" + token);
        return JSON.parseObject(userJson, SysUser.class);
    }

    // 退出登录
    @Override
    public void logout(String token) {
        redisTemplate.delete("user:login" + token);
    }

    // 获取用户列表的方法
    @Override
    public PageInfo<SysUser> findByPage(Integer pageNum, Integer pageSize, SysUserDto sysUserDto) {
        List<SysUser> list = sysUserMapper.findByPage(sysUserDto);
        return new PageInfo<>(list);
    }

    // 用户添加
    @Override
    public void saveSysUser(SysUser sysUser) {
        // 1、判断用户名不能重复
        String userName = sysUser.getUserName();
        SysUser dbSysUser = sysUserMapper.selectUserInfoByUserName(userName);
        if (dbSysUser != null) {
            throw new CustomException(ResultCodeEnum.USER_NAME_IS_EXISTS);
        }
        // 2、输入密码进行加密
        String md5_password = DigestUtils.md5DigestAsHex(sysUser.getPassword().getBytes());
        sysUser.setPassword(md5_password);
        // 3、设置status值
        sysUser.setStatus(1);
        sysUserMapper.save(sysUser);
    }

    // 用户修改
    @Override
    public void updateSysUser(SysUser sysUser) {
        sysUserMapper.update(sysUser);
    }

    // 用户删除
    @Override
    public void deleteById(Long userId) {
        sysUserMapper.delete(userId);
    }

    // 用户分配角色
    // 保存分配数据
    @Transactional
    @Override
    public void doAssign(AssginRoleDto assginRoleDto) {
        // 1、根据userId删除用户之前分配角色数据
        sysRoleUserMapper.deleteByUserId(assginRoleDto.getUserId());
        // 2、重新分配新数据
        List<Long> roleIdList = assginRoleDto.getRoleIdList();
        // 遍历得到每个角色id
        for (Long roleId : roleIdList) {
            sysRoleUserMapper.doAssign(assginRoleDto.getUserId(), roleId);
        }
    }
}
